package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.product.ex.ServiceException;
import cn.tedu.csmall.product.mapper.AlbumMapper;
import cn.tedu.csmall.product.mapper.BrandMapper;
import cn.tedu.csmall.product.mapper.CategoryMapper;
import cn.tedu.csmall.product.mapper.SpuMapper;
import cn.tedu.csmall.product.pojo.dto.SpuAddNewDTO;
import cn.tedu.csmall.product.pojo.entity.Spu;
import cn.tedu.csmall.product.pojo.vo.AlbumStandardVO;
import cn.tedu.csmall.product.pojo.vo.BrandStandardVO;
import cn.tedu.csmall.product.pojo.vo.CategoryStandardVO;
import cn.tedu.csmall.product.service.ISpuService;
import cn.tedu.csmall.product.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class SpuServiceImpl implements ISpuService {

    @Autowired
    SpuMapper spuMapper;
    @Autowired
    AlbumMapper albumMapper;
    @Autowired
    BrandMapper brandMapper;
    @Autowired
    CategoryMapper categoryMapper;

    @Override
    public void addNew(SpuAddNewDTO spuAddNewDTO) {
        log.debug("开始处理【添加spu】业务，新spu：{}", spuAddNewDTO);
        //相册必须存在
        AlbumStandardVO album = albumMapper.getStandardById(spuAddNewDTO.getAlbumId());
        if(album == null){
            String message = "添加spu失败，相册不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        //品牌必须存在
        BrandStandardVO brand = brandMapper.getStandardById(spuAddNewDTO.getBrandId());
        if(brand == null){
            String message = "添加spu失败，品牌不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        //品牌必须未禁用
        if(brand.getEnable() == 0){
            String message = "添加失败，品牌已经被禁用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        //类别必须存在
        CategoryStandardVO category = categoryMapper.getStandardById(spuAddNewDTO.getCategoryId());
        if(category == null){
            String message = "添加spu失败，类别不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        //类别必须未禁用
        if(category.getEnable() == 0){
            String message = "添加失败，类别已经被禁用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        // 类别必须不包含子类别,类别的isParent值不允许为1
        if(category.getIsParent() == 1){
            String message = "添加失败，类别必须不包含子类别！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        Spu spu = new Spu();
        BeanUtils.copyProperties(spuAddNewDTO, spu);
        spuMapper.insert(spu);
    }
}
